import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'

// 1. 导入登录组件
// import Login from '@/views/Login/Login.vue'
const Login = () => import('@/views/Login/Login.vue')
// import Layout from '@/views/Layout/Layout.vue'
const Layout = () => import('@/views/Layout/Layout.vue')

// import Home from '@/views/Home/Home.vue'
const Home = () => import('@/views/Home/Home.vue')
// import User from '@/views/User/User.vue'
const User = () => import('@/views/User/User.vue')

// 导入搜索相关的路由组件
// import Search from '@/views/Search/Search.vue'
const Search = () => import('@/views/Search/Search.vue')
// import SearchResult from '@/views/Search/SearchResult.vue'
const SearchResult = () => import('@/views/Search/SearchResult.vue')

// 导入文章详情页面
// import ArticleInfo from '@/views/Article/ArticleInfo.vue'
const ArticleInfo = () => import('@/views/Article/ArticleInfo.vue')

// 导入编辑用户的页面
// import UserEdit from '@/views/User/UserEdit.vue'
const UserEdit = () => import('@/views/User/UserEdit.vue')

// 导入聊天组件
// import Chat from '@/views/Chat/Chat.vue'
const Chat = () => import('@/views/Chat/Chat.vue')

Vue.use(VueRouter)

// 清空默认的路由规则
// 如果一个路由规则有 name 属性，则它是命名路由
const routes = [
  // 声明登录的路由规则
  { path: '/login', component: Login, name: 'login' },
  // 声明 layout 的路由规则
  {
    path: '/',
    component: Layout,
    children: [
      // 默认子路由
      { path: '', component: Home, name: 'home' },
      // 用户信息页面
      { path: 'user', component: User, name: 'user' }
    ]
  },
  // 搜索相关的路由规则
  { path: '/search', component: Search, name: 'search' },
  // 为当前的路由规则开启 props 传参
  {
    path: '/search/:kw',
    component: SearchResult,
    name: 'search-result',
    props: true
  },
  // 文章详情的路由规则
  {
    path: '/article/:id',
    component: ArticleInfo,
    name: 'art-info',
    props: true
  },
  // 编辑用户信息的路由规则
  {
    path: '/user/edit',
    component: UserEdit,
    name: 'user-edit'
  },
  // 智能聊天的路由规则
  {
    path: '/chat',
    component: Chat,
    name: 'chat'
  }
]

const router = new VueRouter({
  routes
})

// 有权限页面的路径数组
const pagePaths = ['/user', '/user/edit']
// 定义全局前置导航守卫
router.beforeEach((to, from, next) => {
  // 1. 获取到 tokenInfo 这个对象
  const tokenInfo = store.state.tokenInfo
  // 2. 判断用户访问的是否为有权限的页面
  // if (to.path === '/user') {
  if (pagePaths.indexOf(to.path) !== -1) {
    if (!tokenInfo.token) {
      next('/login?pre=' + to.fullPath) // 访问的是有权限的页面，且Token 值不存在，强制跳转到登录页面
    } else {
      next() // 访问的是有权限的页面，而且 token 的值存在
    }
  } else if (to.path === '/login') {
    if (!tokenInfo.token) {
      // 未登录，要访问登录页面
      next()
    } else {
      // 已登录，要访问登录页面
      next(false)
    }
  } else {
    next() // 访问的是普通页面
  }
})

export default router
